﻿var Common = new function () {

    /**
     * 年龄格式化显示
     * @param {any} el
     */
    this.ageFormatter = el => (el.options.value || 0) + ' 岁';
    /**
     * 人数格式化显示
     * @param {any} el
     */
    this.peopleCountFormatter = el => (el.options.value || 0) + ' 个';

    this.boundBusinessKey = el => {
        let $form = el.$from;
        if ($.com.isJqueryObject($form)) {
            let form = $form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                let id = form.getValue('data.Id');
                if ($.com.hasValue(id)) {
                    el.$fields.filter('[data-field="BusinessKey"]').val(id);
                }
            }
        }
    }
    /**
     * 比例格式化显示
     * @param {any} el
     */
    this.inputPercentFormatter = el => $.com.percentFormatter(el.options.value);
    /**
     * 面积格式化显示
     * @param {any} el
     */
    this.inputAreaFormatter = el => $.com.areaFormatter(el.options.value);

    /**
     * 添加 Additional form 的方法
     * @param {any} el
     */
    this.onAddAdditional = el => {
        if ($.com.hasValue(el.options) && $.com.hasValue(el.options.data) && !$.com.hasValue(el.options.data.Index)) {
            let index = 1;
            if ($.com.isJqueryObject(el.$form)) {
                let form = el.$form.data(_config_.form.namespace);
                if ($.com.hasValue(form)) {
                    if (form.options.type === _config_.default.arrayTypeName && $.com.isArray(form.options.data)) {
                        let length = (form.options.data.length > 2) ? form.options.data.length : 2;
                        index = Number(form.options.data[length - 2].Index || 0) + 1;
                    }
                }
            }

            el.options.data.Index = index;
        }
    };

    /**
     * 通过 assignType 和 id 获取对应的 identity.name
     * @param {any} assignType
     * @param {any} id
     */
    this.getByAssignType = (assignType) => $.com.commonFormatter(app.cache.assignType, assignType);

    this.authorizeTypeFormatter = (el, value) => `Devonline.Core.AuthorizeType'${value}'`;

    this.onEditOpened = el => {
        var editorE = el.$el.find('[data-role="kendoEditor"]');
        if (editorE.length > 0) {
            var editor = $(editorE[0]).data("kendoEditor");
            if (editor) {
                const now = new Date();
                editor.options.fileBrowser = {
                    path: now.getFullYear() + "-" + now.getMonth() + "-" + now.getDate(),
                    transport: {
                        read: "https://localhost:9527/api/Attachments/GetFiles",
                        //destroy: "https://demos.telerik.com/kendo-ui/service/filebrowser/destroy",
                        //create: "https://demos.telerik.com/kendo-ui/service/filebrowser/createDirectory",
                        uploadUrl: "https://localhost:9527/api/Attachments/Upload",
                        fileUrl: "https://localhost:9527/api/Attachments/Files/{0}",
                    }
                }

                editor.refresh();
            }
        }
    }

    let editor;
    this.onEditLoaded = el => {
        var Editor = window.wangEditor;
        if (editor != null) {
            editor.destroy();
        }

        editor = new Editor('#editor');
        editor.config.uploadVideoServer = '/api/attachments/upload';
        editor.config.uploadVideoMaxSize = 100 * 1024 * 1024;
        editor.config.uploadVideoAccept = ['mp4'];
        editor.config.uploadVideoHooks = {
            // 上传视频之前
            //before: function (xhr) {
            //    console.log(xhr)

            //    // 可阻止视频上传
            //    return {
            //        prevent: true,
            //        msg: '需要提示给用户的错误信息'
            //    }
            //},
            // 视频上传并返回了结果，视频插入已成功
            success: function (xhr) {
                console.log('success', xhr)
            },
            // 视频上传并返回了结果，但视频插入时出错了
            fail: function (xhr, editor, resData) {
                console.log('fail', resData)
            },
            // 上传视频出错，一般为 http 请求的错误
            error: function (xhr, editor, resData) {
                console.log('error', xhr, resData)
            },
            // 上传视频超时
            timeout: function (xhr) {
                console.log('timeout')
            },
            // 视频上传并返回了结果，想要自己把视频插入到编辑器中
            // 例如服务器端返回的不是 { errno: 0, data: { url : '.....'} } 这种格式，可使用 customInsert
            customInsert: function (insertVideoFn, result) {
                // result 即服务端返回的接口
                console.log('customInsert', result)

                // insertVideoFn 可把视频插入到编辑器，传入视频 src ，执行函数即可
                insertVideoFn(result.data.url)
            }
        }
        var des = el.$form.find('[data-field="description"]');
        editor.config.onchange = function (html) {
            des.val(html).change();
        }

        editor.create();

        if ($.com.hasValue(des.val())) {
            editor.txt.html(des.val());
        }
    }

    /**
     * 用户窗口打开时修正密码框, 编辑模式清空密码, 即不设置默认密码
     * @param {any} el
     */
    this.onUserEditOpened = el => {
        let form = el.$form.data(_config_.form.namespace);
        var $password = form.$fields.filter('[data-field="password"]');
        var $icon = $password.closest('.field').find('.field-group-addon .icon');
        $password.attr('type', 'password');
        $icon.removeClass('fa-eye').addClass('fa-eye-slash');
        if (form.options.data.id) {
            //编辑模式
            $password.val('').change();
        } else {
            $password.val($password.attr('data-value')).change();
        }
    }

    /**
     * 显示隐藏密码
     * 当前对象为密码框
     * @param {any} el
     * @param {any} event
     */
    this.showHidePassword = (el) => {
        var type = el.$el.attr('type');
        var $icon = el.$el.closest('.field').find('.field-group-addon .icon');
        if (type === 'input') {
            //明文模式
            el.$el.attr('type', 'password');
            $icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            //密文模式
            el.$el.attr('type', 'input');
            $icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    }
}

/**
 * 网站通用功能
 */
var _site = new (class _Site {
    /**
     * 绘制菜单
     */
    drawMenu() {
        let $menu = $('.header .user-menu').empty();
        let userInfo = localCache.global.get('userInfo');
        if (userInfo && userInfo.user && userInfo.user.userName) {
            let $userName = $('#_userName');
            if (userInfo.user.userName !== $userName.attr('value')) {
                cache.loadUserInfo(true);
                return;
            }

            $userName.html('[ ' + userInfo.user.name + ' ]');
            if ($.com.isArray(userInfo.resources)) {
                userInfo.resources = userInfo.resources.sort((x, y) => x.code >= y.code ? 1 : -1);
                for (var i = 0; i < userInfo.resources.length; i++) {
                    let resource = userInfo.resources[i];
                    if (resource.children && $.com.isArray(resource.children)) {
                        let sub = '<li role="presentation" class="dropdown-hover">';
                        sub += `<a class="dropdown-toggle" data-toggle="dropdown" href="/${resource.content}" aria-haspopup="true" aria-expanded="false">`;
                        sub += resource.title + `<span class="caret"></span></a>`;
                        sub += `<ul class="dropdown-menu">`;
                        for (var index = 0; index < resource.children.length; index++) {
                            var child = resource.children[index];
                            sub += `<li class="nav-item"><a class="nav-link text-dark" href="/${child.content}">${child.title}</a></li>`;
                        }

                        sub += `</ul>`;
                        sub += `</li>`;
                        $menu.append(sub);
                    } else {
                        $menu.append(`<li class="nav-item"><a class="nav-link text-dark" href="/${resource.content}">${resource.title}</a></li>`);
                    }
                }
            }

            var spans = $('.header .user-menu .item');
            if (spans.length > 0) {
                for (var i = 0; i < spans.length; i++) {
                    $(spans[i]).mouseenter(function () {
                        var that = $(this).find('.user-menu-drop');
                        that.show();
                        $('.user-menu-drop').not(that).hide();
                    })

                    $(spans[i]).find('.user-menu-drop').mouseleave(function () {
                        $(this).hide();
                    });
                }
            }
        }
    }

    /**
     * 创建通讯器
     */
    loadCommunitor() {
        if (!app.communitor) {
            let userInfo = localCache.global.get('userInfo');
            if (userInfo && userInfo.dcs && userInfo.user && userInfo.user.name) {
                app.communitor = new Communicator({
                    host: userInfo.dcs,
                    user: userInfo.user.userName,
                    client: "hmf.admin",
                    onReceive: message => {
                        switch (message.type) {
                            case MessageType.Cache:
                                if (message.content == "UserInfo") {
                                    cache.loadUserInfo(true);
                                } else if (message.content == "Parameter") {
                                    cache.loadParameters(true);
                                }
                                break;
                            case MessageType.Text:
                                app.info(`收到了来自用户: ${message.sender} 发来的消息: \n"${message.content}"`, { timer: 5000 });
                                break;
                            case MessageType.Data:
                            default:
                                console.log(message.content);
                                break;
                        }
                    },
                    onNotice: message => {
                        app.info(`收到通知: "${message.content}"`, { timer: 10000 });
                    },
                    onWarning: message => {
                        app.warning(`收到警告: "${message.content}"`);
                    },
                    onError: message => {
                        app.error(`收到错误: "${message.content}"`);
                    }
                });
                app.communitor.start();
            }
        }
    }

    /**
     * 系统使用的四种消息类型
     */
    get messageType() {
        return cache.messageType.get(x => x.key == 'text' || x.key == 'notice' || x.key == 'announcement' || x.key == 'news');
    }

    /**
    * 统计查询用到的时间刻度
    */
    get timeKind() {
        return cache.timeKind.get(x => x.key == 'infinite' || x.key == 'year' || x.key == 'month' || x.key == 'day');
    }
});